package com.tomato.study.caffeine.modules.user.service.impl;

import com.tomato.study.caffeine.modules.user.entity.UserInfo;
import com.tomato.study.caffeine.modules.user.mapper.UserInfoMapper;
import com.tomato.study.caffeine.modules.user.service.UserInfoService;
import com.tomato.study.caffeine.modules.user.vo.UserInfoRequest;
import com.tomato.study.caffeine.modules.user.vo.UserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 用户信息服务实现类
 *
 * @author lizhifu
 * @date 2022/5/6
 */
@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    @CachePut(value = "user", key = "#userInfoRequest.id")
    public UserInfo addUserInfo(UserInfoRequest userInfoRequest) {
        log.info("添加了id、key为" + userInfoRequest.getId() + "的数据缓存");
        UserInfo userInfo = new UserInfo().setId(userInfoRequest.getId()).setName(userInfoRequest.getName());
        userInfoMapper.insert(userInfo);
        return userInfo;
    }

    @Override
    @Cacheable(value = "user",key = "#id")
    public UserInfo getById(Integer id) {
        log.info("查询了id、key为" + id + "的数据缓存");
        UserInfo userInfo = userInfoMapper.selectById(id);
        return userInfo;
    }

    @Override
    @CacheEvict(value = "user", key = "#id")
    public void deleteById(Integer id) {
        log.info("删除了id、key为" + id + "的数据缓存");
        userInfoMapper.deleteById(id);
    }
}
